package 笔试.面试手撕;



import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author:谢君臣
 * @Date:2021/9/3-11:27
 * @version:1.0
 * @function:
 */
public class 静态代理 {
    public static void main(String[] args) {
        userDao userDao = (笔试.面试手撕.userDao) new userDaoProxy().getProxy(new userDaoImpl());
        userDao.add();

        CglibProxyUserService proxyUserService = new CglibProxyUserService(UserService.class);
        UserService proxy = (UserService) proxyUserService.getProxy();
        System.out.println(proxy.add());
    }
}
interface userDao{
    void add();
}
class userDaoImpl implements userDao{
    @Override
    public void add() {
        System.out.println(this.getClass().getName()+"实现的方法");
    }
}

class userDaoProxy implements InvocationHandler{
    private Object target;
    Object getProxy(Object target){
        this.target = target;
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("前置方法");
        Object result = method.invoke(target, args);
        return result;
    }
}
class UserService{
    String add(){
        System.out.println("UserService-add");
        return "UserService-ok";
    }
}
class CglibProxyUserService implements MethodInterceptor {
    private Enhancer enhancer;
    private Object proxy;

    public CglibProxyUserService() {
        enhancer = new Enhancer();
    }
    public CglibProxyUserService(Class proxyClass) {
        enhancer = new Enhancer();
        enhancer.setSuperclass(proxyClass);
        enhancer.setCallback(this);
        proxy = enhancer.create();
    }
    public Object getProxy() {
        return proxy;
    }
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println(method.getName());
        Object result = methodProxy.invokeSuper(o, objects);
        return result;
    }
}
